<?php
declare (strict_types = 1);
namespace app\course\logic\live;

use app\course\model\live\Live as LiveModel;
use think\facade\Request;
use Tencent\TLSSigAPIv2;
use app\admin\logic\system\Config as SystemConfig;
use app\common\exception\LogicException;
use app\course\logic\base\CourseSection;
use app\course\model\live\CourseSectionLive;
use app\user\logic\teacher\Teacher;

/**
 * 前台接口逻辑层
 */
class Live extends LiveModel
{

	/**
     * 互动课堂签名
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-29
     * @param    Request                        $request [description]
     * @return   [type]                                  [description]
     */
    public function userSignV2()
    {
    	$section_id = Request::get('section_id');
    	$mid 		= request()->mid;

        $config = SystemConfig::get('course.live.config.tic', []);
        if (empty($config)) {
            throw new LogicException('服务暂不可用','互动课堂配置错误');
        }

        $api = new TLSSigAPIv2($config['sdk_appid'], $config['key']);
        $sig = $api->genSig($mid);

        $data = $this->getRoomUserInfo($section_id, $mid);

        $data['sdk_appid'] = $config['sdk_appid'];
        $data['user_sig']  = $sig;

        return $data;
    }

    public function getRoomUserInfo($section_id = 0, $mid = 0)
    {
        // 获取用户身份及房间号
        $section = app(CourseSection::class)->with(['teacher_id', 'course_info'])->findOrFail($section_id);

        if ( !$section->is_last || $section->course_type != 2 ) {
            throw new LogicException("未找到课时");
        }

        $teacher_id      = $section->teacher_id;
        $teacher_user_id = app(Teacher::class)->getTeacherUserId($teacher_id);
        $identity        = $mid == $teacher_user_id ? 1 : 0;

        $now_time = time();
        $tea_time = 15; // 讲师开课限制时间，可后台配置
        $stu_time = 5;  // 学生入课时间限制，可后台配置

        if ( $identity ) {
            if ( $section->start_time - $tea_time*60 > $now_time ) {
                throw new LogicException("直播未开始，请于开播前" . $tea_time . "内分钟进入");
            }
        } else {
            // 房间未创建
            $live_data = app(CourseSectionLive::class)->where('room_no', $section_id)->findOrEmpty();

            if ( ($section->start_time - $stu_time*60 > $now_time) || $live_data->isEmpty() ) {
                throw new LogicException("直播未开始");
            }
        }

        $oneonone           = $section->course_info->limit_buy_count == 1 ? 1 : 0;
        $course_live_type   = $oneonone ? 3 : $section->course_info->course_live_type;

        $data = [
            'user_id'      => $mid,
            'teacher_id'   => $teacher_id,
            'identity'     => $identity,
            'room_no'      => intval($section_id),
            'section_name'      => $section->title,
            'course_live_type'  => $course_live_type,
        ];

        return $data;
    }
}
